package com.china08.yxyapi.api.manage.tec.teaching.lecture.prepare;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.http.MediaType;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.china08.yxyapi.api.YxyApiBaseController;
import com.china08.yxyapi.entity.db.res.YxyResResource;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack;
import com.china08.yxyapi.entity.mg.lecture.YxyLecturePrePack.Res;
import com.china08.yxyapi.entity.mg.lecture.YxyLectureRes;
import com.china08.yxyapi.model.YxyApiPageReqModel;
import com.china08.yxyapi.model.YxyApiRespModel;
import com.china08.yxyapi.repository.db.YxyLectureFeedBackRepository;
import com.china08.yxyapi.repository.db.YxyResResourceRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLecturePrePackRepository;
import com.china08.yxyapi.repository.mg.lecture.YxyLectureResRepository;
import com.china08.yxyapi.util.DateToolUtils;

/**
 * 老师 ---备授课--查询我的备课包
 * 
 */
@CrossOrigin
@RestController
public class LectureSchPrePackController extends YxyApiBaseController {

    @Autowired
    private YxyLecturePrePackRepository yxyLecturePrePackRepository;

    @Autowired
    private YxyLectureResRepository yxyLectureResRepository;

    @Autowired
    private YxyResResourceRepository YxyResResourceRepository;

    @Autowired
    private YxyLectureFeedBackRepository yxyLectureFeedBackRepository;

    @RequestMapping(value = "/api_yw/manage/tec/teaching/lecture/prepack/sch", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public Object process(HttpServletRequest request, HttpServletResponse response, @RequestBody ReqModel req) {
        String userId = getProfile(request, response).getId();
        String userNick = getProfile(request, response).getUserNick();
        String schoolId = getProfile(request, response).getSchoolId();
        Pageable pageable = req.getPageable(Direction.DESC, "createdDate");
        Page<YxyLecturePrePack> page = null;
        String userVip = getProfile(request, response).getResVip();
        // 自己未删除的
        if (StringUtils.isNotBlank(req.keyword)) {
            page = yxyLecturePrePackRepository
                    .findByUserIdAndSchoolIdAndBookcontentsIdAndPackNameContainingAndIsDeleteNot(userId, schoolId,
                            req.bookContent, req.keyword, 1, pageable);
        } else {
            page = yxyLecturePrePackRepository.findByUserIdAndSchoolIdAndBookcontentsIdAndIsDeleteNot(userId, schoolId,
                    req.bookContent, 1, pageable);
        }
        List<RespModel> listModel = new ArrayList<RespModel>();
        for (YxyLecturePrePack yxyLecturePrePack : page) {
            RespModel model = new RespModel();
            List<ResModel> resModels = new ArrayList<ResModel>();
            Integer resSize = 0;
            if (yxyLecturePrePack.getResources() != null) {
                for (Res respModel : yxyLecturePrePack.getResources()) {
                    List<Integer> resUsed = new ArrayList<>();
                    ResModel resModel = new ResModel();
                    resModel.resId = respModel.getResourceId();
                    resModel.formatId = respModel.getFormatId();
                    resModel.title = respModel.getResourceName();
                    resModel.orderNum = respModel.getOrderNum() != null ? respModel.getOrderNum() : 0;
                    resModel.courseType = respModel.getCourseType();
                    resModel.resUrl = respModel.getResourceUrl();
                    YxyResResource yxyResResource = YxyResResourceRepository.findById(respModel.getResourceId());
                    if (null != yxyResResource) {
                        resModel.isHighQualityYx = yxyResResource.getIsHighQualityYx();
                        resModel.vip = yxyResResource.getIsVip();
                    } else {
                        resModel.isHighQualityYx = 0;
                        resModel.vip = false;
                    }
                    resModel.userVip = userVip;
                    Integer fileSize = respModel.getFileSize();
                    if (null != fileSize) {
                        resModel.fileSize = fileSize;
                    } else {
                        resModel.fileSize = 0;
                    }
                    Integer usesHomework = respModel.getUsesHomework();
                    if (usesHomework == 1) {
                        usesHomework = 3;
                    } else {
                        usesHomework = 5;
                    }
                    Integer usesProview = respModel.getUsesProview();
                    if (usesProview == 1) {
                        usesProview = 2;
                    } else {
                        usesProview = 5;
                    }
                    Integer usesTeaching = respModel.getUsesTeaching();
                    if (usesTeaching == 1) {
                        usesTeaching = 1;
                    } else {
                        usesTeaching = 5;
                    }
                    Integer usesTest = respModel.getUsesTest();
                    if (usesTest == 1) {
                        usesTest = 4;
                    } else {
                        usesTest = 5;
                    }
                    resUsed.add(usesTeaching);
                    resUsed.add(usesProview);
                    resUsed.add(usesHomework);
                    resUsed.add(usesTest);
                    resModel.resUsed = resUsed;
                    if (resModel.courseType == 0) {
                        List<String> quesIds = new ArrayList<String>();
                        YxyLectureRes lectureRes = yxyLectureResRepository.findByResourceId(resModel.resId);
                        quesIds = lectureRes.getQuesIds();
                        resModel.quesIds = quesIds;
                    }
                    resModels.add(resModel);
                }
                resSize = resModels.size();
            }
            resModels = resModels.stream().sorted((p1, p2) -> p1.orderNum.compareTo(p2.orderNum))
                    .collect(Collectors.toList());
            model.id = yxyLecturePrePack.getId();
            model.title = yxyLecturePrePack.getPackName();
            model.count = resSize;
            model.userVip = userVip;
            model.bookcontentsId = yxyLecturePrePack.getBookcontentsId();
            model.bookcontentsName = yxyLecturePrePack.getBookcontentsName();
            model.schoolId = yxyLecturePrePack.getSchoolId();
            model.phaseId = yxyLecturePrePack.getPhaseId();
            model.phaseName = yxyLecturePrePack.getPhaseName();
            model.subjectId = yxyLecturePrePack.getSubjectId();
            model.subjectName = yxyLecturePrePack.getSubjectName();
            model.versionId = yxyLecturePrePack.getVersionId();
            model.versionName = yxyLecturePrePack.getVersionName();
            model.areaIdProvince = yxyLecturePrePack.getAreaIdProvince();
            model.areaIdCity = yxyLecturePrePack.getAreaIdCity();
            model.areaIdDistrict = yxyLecturePrePack.getAreaIdDistrict();
            model.auditStatus = yxyLecturePrePack.getAuditStats();
            model.isHighQualityYx = yxyLecturePrePack.getIsHighQualityYx();
            model.isVip = yxyLecturePrePack.getIsVip();
            long countByPrepackId = yxyLectureFeedBackRepository.countByPrepackId(yxyLecturePrePack.getId());
            model.feedBackCount = countByPrepackId;
            model.packName = yxyLecturePrePack.getPackName();
            model.ranks = yxyLecturePrePack.getRanks();
            model.isView = yxyLecturePrePack.getIsView();
            Long fileSize = yxyLecturePrePack.getPackSize();
            if (null != fileSize) {
                Double valueOf = Double.valueOf(fileSize + "");
                Double file = valueOf / 1024;
                BigDecimal bg = new BigDecimal(file);
                double f1 = bg.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
                model.packSize = f1;
            } else {
                model.packSize = 0.0;
            }
            model.schoolNick = yxyLecturePrePack.getSchoolNick();
            model.userNick = yxyLecturePrePack.getUserNick();
            if (schoolId.equals("ff80808142a16af00142a1a60f010006")
                    || "ff80808142a16af00142a1a60f010006".equals(yxyLecturePrePack.getSchoolId())) {
                model.schoolNick = "";
            }
            model.share = yxyLecturePrePack.getShare();
            model.createdDateFormat = DateToolUtils.format(yxyLecturePrePack.getCreatedDate(),
                    DateToolUtils.FORMAT_SHORT_YMD);
            model.resources = resModels;
            if (yxyLecturePrePack.getReferencUserId() != null
                    && !yxyLecturePrePack.getReferencUserId().equals(userId)) {
                model.isHidden = "0";
            } else {
                model.isHidden = "1";
            }
            listModel.add(model);
        }
        Page<RespModel> respPage = new PageImpl<>(listModel, pageable, page.getTotalElements());

        return respPage;
    }

    protected static class ReqModel extends YxyApiPageReqModel {

        public String bookContent;

        public String keyword;

        public void check() {
            Assert.notNull(StringUtils.defaultIfBlank(bookContent, null), "请选择目录");
        }

    }

    protected class ResModel {
        public String resId;
        public String formatId;
        public String title;
        public Integer orderNum;
        public Integer courseType;
        public String resUrl;
        public List<Integer> resUsed;
        public List<String> quesIds;
        public Integer fileSize;
        public boolean vip;
        public Integer isHighQualityYx;
        public String userVip;
    }

    protected static class RespModel extends YxyApiRespModel {
        public String id;
        public String title;
        public int count;
        public Integer share;
        // 贡献者学校名称
        public String schoolNick;
        // 贡献者名称
        public String userNick;
        // 创建时间（收录时间）
        public String createdDateFormat;
        // 资源
        public List<ResModel> resources;
        // 备课包大小
        public Double packSize;

        public String userVip;
        // 是否隐藏共享
        public String isHidden;

        public String packName;

        public String bookcontentsId;

        public String bookcontentsName;

        public String schoolId;

        public String auditUserName = "";

        public String phaseId;

        public String phaseName;

        public String subjectId;

        public String subjectName;

        public String versionId;

        public String versionName;

        public String areaIdProvince;

        public String areaIdCity;

        public String areaIdDistrict;

        public String status = "0";

        public String downReason = "";

        public Integer isHighQualityYx;

        public Integer isVip;

        public long feedBackCount;

        public Integer ranks;

        public Integer isView;

        public Integer auditStatus;
    }
}
